//
import { Toast } from 'vant'
import trim from 'lodash/trim'
export default function pdaShowMessage({ vm, action, done, callbackData }) {
  const useLastData = action.extension.useLastData.value
  const message = action.extension.message.value
  const staticList = message.split(/#{.*?}/gi)
  const variableList = message.match(/#{(.+?)\}/g)
  console.log('message', message, vm)
  let messageContent = ''
  if (useLastData) {
    // 如果使用上次任务数据，则通过key获取消息内容

    if (message.indexOf('->') !== -1) {
      const fieldList = message.split('->')
      messageContent = callbackData
      fieldList.forEach((fieldItem) => {
        // 如果没有后续值则不继续往下取值
        if (messageContent[trim(fieldItem)] === undefined) return
        messageContent = messageContent[trim(fieldItem)]
      })
    } else {
      messageContent = callbackData[message]
    }
  } else {
    if (variableList && variableList.length) {
      // 如果有配置变量 则先获取变量值
      variableList.forEach((variableItem, index) => {
        let variableContent = ''
        variableItem = trim(variableItem.slice(2, -1))
        if (variableItem.indexOf('->') !== -1) {
          const fieldList = variableItem.split('->')
          variableContent = callbackData
          fieldList.forEach((fieldItem) => {
            // 如果没有后续值则不继续往下取值
            if (variableContent[trim(fieldItem)] === undefined) return
            variableContent = variableContent[trim(fieldItem)]
          })
        } else {
          variableContent = callbackData[variableItem]
        }
        staticList.splice(index * 2 + 1, 0, variableContent)
      })
      messageContent = staticList.join('')
    } else {
      messageContent = message
    }
  }
  console.log('messageContent', messageContent)
  if (messageContent && messageContent.includes('<br/>')) {
    messageContent = messageContent.replace('<br/>', '')
  }

  Toast(messageContent)
  done(null, {})
}
